<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\View;

//use Workerman\Worker;
//use Workerman\Connection\AsyncTcpConnection;

class Index extends BaseController
{
    public function index()
    {
        echo 666;die;
        return View::fetch('index');
    }

    public function index2()
    {
        return View::fetch('index2');
    }

    public function push()
    {
        /*$socket = new \Swoole\Coroutine\Socket(AF_INET, SOCK_DGRAM, 0);
        $socket->bind('39.108.36.131', 2348);
        $client_map = [];
        for ($c = 128; $c--;) {
            for ($n = 0; $n < 100; $n++) {
               $recv = $socket->recvfrom($peer);
               $client_uid = "{$peer['address']}:{$peer['port']}";
               $id = $client_map[$client_uid] = ($client_map[$client_uid] ?? -1) + 1;
               assert($recv === "Client: Hello #{$id}!");
               $socket->sendto($peer['address'], $peer['port'], "Server: Hello #{$id}!");
          }
        }
        $socket->close();*/


        /*$cli = \Swoole\Coroutine\Http\Client('39.108.36.131', 2348);
        $ret = $cli->upgrade("/");
        $data = [
            'type' => 'text',
            'fromUid' => 20,
            'msg'  => 'test66666'
        ];
        if($ret){
            $cli->push(json_encode($data));
            $cli->close();
        }*/
    }


    public function send()
    {
        $message = 'testmsg==='.time();
        $pushApiUrl = "http://39.108.36.131:2120/";
        $postData = [
            "method" => "text",
            "msg" => $message
        ];

        $postData["id"] = '10';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $pushApiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec($ch);
        curl_close($ch);

        var_dump($return);
    }

    public function issue($id, $url)
    {
        $key = "sufa123123";
        $time = time();
        $token = [
            'iss' => 'http://test.com', //签发者
            'aud' => 'http://test.com',//接收者
            'iat' => $time, //签发时间
            'nbf' => $time, //生效时间
            'exp' => $time+7200, //过期时间
            'data' => [
                'uid' => $id,
                'name' => 'peter'.$id,
                'service_url' => $url
            ]
        ];

        return \Firebase\JWT\JWT::encode($token, $key);
    }
}
